package com.zhsj.OkeHomeConsumption.ui.activity;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Interpolator;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.google.gson.Gson;
import com.hjq.bar.TitleBar;
import com.hjq.dialog.MessageDialog;
import com.orhanobut.hawk.Hawk;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.yintong.secure.model.PayResult;
import com.zhsj.OkeHomeConsumption.R;
import com.zhsj.OkeHomeConsumption.common.Constants;
import com.zhsj.OkeHomeConsumption.common.MyActivity;
import com.zhsj.OkeHomeConsumption.common.OkeHomeConsumptionApi;
import com.zhsj.OkeHomeConsumption.common.lianlianpay.utils.BaseHelper;
import com.zhsj.OkeHomeConsumption.common.lianlianpay.utils.MobileSecurePayer;
import com.zhsj.OkeHomeConsumption.common.lianlianpay.utils.PayOrder;
import com.zhsj.OkeHomeConsumption.empty.AuthResult;
import com.zhsj.OkeHomeConsumption.empty.FormalUserInfo;
import com.zhsj.OkeHomeConsumption.network.HttpClient;
import com.zhsj.OkeHomeConsumption.network.JsonResponseHandler;
import com.zhsj.OkeHomeConsumption.other.TimeChecker;
import com.zhsj.OkeHomeConsumption.other.URLEntity;
import com.zhsj.OkeHomeConsumption.ui.activity.wallet.ProgressDrawableAlertDialog;
import com.zhsj.OkeHomeConsumption.ui.activity.wallet.TimeOutHandler;
import com.zhsj.OkeHomeConsumption.utils.JsonUtils;
import com.zhsj.OkeHomeConsumption.utils.LogUtils;
import com.zhsj.OkeHomeConsumption.utils.SignUtil;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;

import static com.zhsj.OkeHomeConsumption.common.Constants.SHARED_PERFERENCE_USERINFO;

/**
 * author : Xingdx
 * <p>
 * time   : 2018/10/18
 * desc   : 选择支付方式
 */
public final class PayAmountActivity extends MyActivity implements View.OnClickListener {

    /**
     * loading
     */
    private ProgressDrawableAlertDialog pDialogUtils = null;
    /**
     * @Fields timeChecker : TODO
     */
    private TimeChecker timeChecker = null;

    private TextView price_text = null;//支付金额

    private TextView name_text = null;//支付类型

    private LinearLayout lianlian_pay = null;

    private LinearLayout weiixn_pay = null;

    private LinearLayout jifen_pay = null;

    //支付宝支付
    private LinearLayout zhifubao_pay = null;

    private TitleBar mTitleBar;

    private String price = "";

    private String usertype = null;//如果是交付定金的话就是话用户类型
    //pay_flage 支付类型（0 交纳保证金）
    private int pay_flage = -1;

    //店铺名称
    private String shopname = "";

    //二维码字符串
    private String er_code = null;

    //店铺id
    private int shopid = -1;

    private FormalUserInfo userInfo = null;

    // 0:代表订单支付  1 代表款项支付
    private Bundle bundle = null;

    //1 定金支付 2 扫码支付
    private int SDK_PAY_FLAG = -1;

    //支付宝订单信息
    private String orderInfo = null;   // 订单信息

    @Override
    protected int getLayoutId() {
        return R.layout.activity_payamount;
    }

    @Override
    protected int getTitleId() {
        return R.id.tb_copy_title;
    }

    @Override
    protected void initView() {
        userInfo = Hawk.get(Constants.SHARED_PERFERENCE_USERINFO);
        ;
        // 网络计时器
        timeChecker = new TimeChecker(TimeOutHandler.timeOutHandler, Constants.TIME_OUT);
        // 进度条
        pDialogUtils = new ProgressDrawableAlertDialog(getActivity());
        price_text = findViewById(R.id.price_text);
        name_text = findViewById(R.id.name_text);
        lianlian_pay = findViewById(R.id.lianlian_pay);
        weiixn_pay = findViewById(R.id.wx_pay);
        zhifubao_pay = findViewById(R.id.zhifubao_pay);
        jifen_pay = findViewById(R.id.jifen_pay);
        mTitleBar = (TitleBar) findViewById(R.id.tb_copy_title);
    }

    @Override
    protected void initData() {
        bundle = new Bundle();
        lianlian_pay.setOnClickListener(this);
        weiixn_pay.setOnClickListener(this);
        zhifubao_pay.setOnClickListener(this);
        jifen_pay.setOnClickListener(this);

        //pay_flage 支付类型（0 交纳保证金,1支付订单）
        pay_flage = getIntent().getIntExtra("pay_flage", -1);
        price = getIntent().getStringExtra("price");
        switch (pay_flage) {
            case 0:
                usertype = getIntent().getStringExtra("usertype");
                mTitleBar.setTitle("交纳保证金");
                jifen_pay.setVisibility(View.GONE);
                break;
            case 1:
                shopid = getIntent().getIntExtra("shopid", -1);
                er_code = getIntent().getStringExtra("code");
                shopname = getIntent().getStringExtra("shopname");
                name_text.setText(shopname);

                mTitleBar.setTitle("订单支付");
                break;
        }
        price_text.setText("¥" + price);
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.wx_pay:
                switch (pay_flage) {
                    case 0:
                        //支付保证金
                        weixin_pay(usertype, price);
                        break;
                    case 1:
                        //支付订单
                        if (price.equals("")) {
                            toast("请输入支付金额");
                            return;
                        }
                        Gson gson = new Gson();
                        Map<String, Object> mapjson = new HashMap<>();
                        mapjson.put("amount", price);
                        mapjson.put("ip", "192.168.0.1");
                        mapjson.put("optType", "1");//必传,操作类型[1-app端，2-微信小程序端]
                        mapjson.put("payType", "2");//支付类型,1-连连，2-微信，3-积分,该字段目前可以传
                        mapjson.put("qrCodeStr", er_code);//二维码对应的字符串序列 ,
                        mapjson.put("shopId", shopid);//店铺id
                        String lifeCityCopartnerDTO = gson.toJson(mapjson);//map转json字符串
                        wechat_pay(lifeCityCopartnerDTO);
                        break;
                }
                break;
            case R.id.lianlian_pay:
                //连连支付
                switch (pay_flage) {
                    case 0:
                        //支付保证金
                        break;
                    case 1:
                        //支付订单
                        if (price.equals("")) {
                            toast("请输入支付金额");
                            return;
                        }
                        Gson gson = new Gson();
                        Map<String, Object> mapjson = new HashMap<>();
                        mapjson.put("amount", price);
                        mapjson.put("ip", "192.168.0.1");
                        mapjson.put("optType", "1");//必传,操作类型[1-app端，2-微信小程序端]
                        mapjson.put("payType", "1");//支付类型,1-连连，2-微信，3-积分,该字段目前可以传
                        mapjson.put("qrCodeStr", er_code);//二维码对应的字符串序列 ,
                        mapjson.put("shopId", shopid);//店铺id
                        String lifeCityCopartnerDTO = gson.toJson(mapjson);//map转json字符串
                        if (userInfo.getUserAuthentic() != null) {
                            PayPost(lifeCityCopartnerDTO);
                        } else {
                            // 实名认证
                            Bundle bundle = new Bundle();
                            bundle.putSerializable("formalUserInfo", userInfo);
                            startActivity(new Intent(this, MineUserAuthFragment.class)
                                    .putExtras(bundle));

                        }
                        break;
                }

                break;
            case R.id.jifen_pay:
                //积分支付
                integral2cash(price);
                break;
            case R.id.zhifubao_pay:
                //支付宝支付
                switch (pay_flage) {
                    case 0:
                        //支付保证金
                        SDK_PAY_FLAG = 1;
                        zhifubao_pay(usertype, price);
                        break;
                    case 1:
                        SDK_PAY_FLAG = 2;
                        //支付订单
                        if (price.equals("")) {
                            toast("请输入支付金额");
                            return;
                        }
                        Gson gson = new Gson();
                        Map<String, Object> mapjson = new HashMap<>();
                        mapjson.put("amount", price);
                        mapjson.put("ip", "192.168.0.1");
                        mapjson.put("optType", "1");//必传,操作类型[1-app端，2-微信小程序端]
                        mapjson.put("payType", "4");//支付类型,1-连连，2-微信，3-积分,该字段目前可以传
                        mapjson.put("qrCodeStr", er_code);//二维码对应的字符串序列 ,
                        mapjson.put("shopId", shopid);//店铺id
                        String lifeCityCopartnerDTO = gson.toJson(mapjson);//map转json字符串
                        zfb_pay(lifeCityCopartnerDTO);
                        break;
                }
                break;

        }
    }

    /**
     * @param
     * @return weixin款项支付保证金
     * 创建时间：2017/3/7 12:29
     */
    public void weixin_pay(String lifeUserTye, String amount) {
        // TODO Auto-generated method stub
        // post传参使用的HashMap
        HashMap<String, String> paramMaps = new HashMap<String, String>();
        // 生成sign值所使用的HashMap
        final HashMap<String, String> mLogOnHashMap = new HashMap<String, String>();
        // mParamHashMap.put("token", Constants.TOKEN);
        mLogOnHashMap.put("v", Constants.APPVERSION);
        mLogOnHashMap.put("t", Constants.TIME);
        mLogOnHashMap.put("deviceToken", Constants.DEVICETOKEN);
        mLogOnHashMap.put("client", Constants.CLIENT);
        LogUtils.e("PayPost time =", Constants.TIME);
        mLogOnHashMap.put("deviceId", URLEntity.getInstance().getImei());
        mLogOnHashMap.put("platform", Constants.PLAFORM);


        mLogOnHashMap.put("lifeUserTye", String.valueOf(lifeUserTye));
        paramMaps.put("lifeUserTye", String.valueOf(lifeUserTye));

        mLogOnHashMap.put("money", String.valueOf(amount));
        paramMaps.put("money", String.valueOf(amount));

        mLogOnHashMap.put("ip", "192.168.0.1");
        paramMaps.put("ip", "192.168.0.1");

        mLogOnHashMap.put("optType", "1");
        paramMaps.put("optType", "1");


        // 网络计时器及线程
        TimeOutHandler.pDialogUtils = pDialogUtils;
        pDialogUtils.show();
        timeChecker.start();
        // 获取sign签名
        Constants.SIGN = SignUtil.getInstance().getSign(mLogOnHashMap);
        HttpClient.get(OkeHomeConsumptionApi.ELVDOU_WXPAY, paramMaps, new JsonResponseHandler() {

            @Override
            public void onSuccess(int statusCode, String content) {
                // TODO Auto-generated method stub
                super.onSuccess(statusCode, content);
                timeChecker.check();
                pDialogUtils.dismiss();
                TimeOutHandler.pDialogUtils = null;
                try {
                    JSONTokener jsonT = new JSONTokener(content);
                    JSONObject jsonOBJ = (JSONObject) jsonT.nextValue();
                    String code = jsonOBJ.optString("code");
                    String message = jsonOBJ.optString("message");
                    if (code.equals("N000000")) {
                        JSONObject jSONObject = jsonOBJ.optJSONObject("data");
                        final IWXAPI wx_api = WXAPIFactory.createWXAPI(getActivity(), null);
                        wx_api.registerApp("wx50199addaec9e004");
                        PayReq req = new PayReq();
                        req.packageValue = jSONObject.getString("package");
                        req.sign = jSONObject.getString("sign");
                        req.timeStamp = jSONObject.getString("timestamp");
                        req.appId = jSONObject.getString("appid");
                        req.nonceStr = jSONObject.getString("noncestr");
                        req.partnerId = jSONObject.getString("partnerid");
                        req.prepayId = jSONObject.getString("prepayid");
                        req.extData = "Pay";
                        wx_api.sendReq(req);
                        finish();
                        //  showShortToast("正常吊起微信支付");
                        // token过期
                    }
                } catch (JSONException ex) {
                    LogUtils.e("DownPaymentPost", "付首期款请求失败 ");
                }
            }
        });
    }

    /**
     * @param
     * @return weixin支付会员订单
     * 创建时间：2017/3/7 12:29
     */
    public void wechat_pay(String lifeUserTye) {
        // TODO Auto-generated method stub
        // post传参使用的HashMap
        HashMap<String, String> paramMaps = new HashMap<String, String>();
        // 生成sign值所使用的HashMap
        final HashMap<String, String> mLogOnHashMap = new HashMap<String, String>();
        // mParamHashMap.put("token", Constants.TOKEN);
        mLogOnHashMap.put("v", Constants.APPVERSION);
        mLogOnHashMap.put("t", Constants.TIME);
        mLogOnHashMap.put("deviceToken", Constants.DEVICETOKEN);
        mLogOnHashMap.put("client", Constants.CLIENT);
        LogUtils.e("PayPost time =", Constants.TIME);
        mLogOnHashMap.put("deviceId", URLEntity.getInstance().getImei());
        mLogOnHashMap.put("platform", Constants.PLAFORM);


        // 网络计时器及线程
        TimeOutHandler.pDialogUtils = pDialogUtils;
        pDialogUtils.show();
        timeChecker.start();
        // 获取sign签名
        Constants.SIGN = SignUtil.getInstance().getSign(mLogOnHashMap);
        HttpClient.posttwo(OkeHomeConsumptionApi.ELVDOU_WECHAT, lifeUserTye, new JsonResponseHandler() {

            @Override
            public void onSuccess(int statusCode, String content) {
                // TODO Auto-generated method stub
                super.onSuccess(statusCode, content);
                timeChecker.check();
                pDialogUtils.dismiss();
                TimeOutHandler.pDialogUtils = null;
                try {
                    JSONTokener jsonT = new JSONTokener(content);
                    JSONObject jsonOBJ = (JSONObject) jsonT.nextValue();
                    String code = jsonOBJ.optString("code");
                    String message = jsonOBJ.optString("message");
                    if (code.equals("N000000")) {
                        JSONObject jSONObject = jsonOBJ.optJSONObject("data");
                        final IWXAPI wx_api = WXAPIFactory.createWXAPI(getActivity(), null);
                        wx_api.registerApp("wx50199addaec9e004");
                        PayReq req = new PayReq();
                        req.packageValue = jSONObject.getString("package");
                        req.sign = jSONObject.getString("sign");
                        req.timeStamp = jSONObject.getString("timestamp");
                        req.appId = jSONObject.getString("appid");
                        req.nonceStr = jSONObject.getString("noncestr");
                        req.partnerId = jSONObject.getString("partnerid");
                        req.prepayId = jSONObject.getString("prepayid");
                        req.extData = "Pay";
                        wx_api.sendReq(req);
                        finish();
                        //  showShortToast("正常吊起微信支付");
                        // token过期
                    }
                } catch (JSONException ex) {
                    LogUtils.e("DownPaymentPost", "付首期款请求失败 ");
                }
            }
        });
    }

    /**
     * @param
     * @return 支付宝支付会员订单
     * 创建时间：2017/3/7 12:29
     */
    public void zfb_pay(String lifeUserTye) {
        // TODO Auto-generated method stub
        // post传参使用的HashMap
        HashMap<String, String> paramMaps = new HashMap<String, String>();
        // 生成sign值所使用的HashMap
        final HashMap<String, String> mLogOnHashMap = new HashMap<String, String>();
        // mParamHashMap.put("token", Constants.TOKEN);
        mLogOnHashMap.put("v", Constants.APPVERSION);
        mLogOnHashMap.put("t", Constants.TIME);
        mLogOnHashMap.put("deviceToken", Constants.DEVICETOKEN);
        mLogOnHashMap.put("client", Constants.CLIENT);
        LogUtils.e("PayPost time =", Constants.TIME);
        mLogOnHashMap.put("deviceId", URLEntity.getInstance().getImei());
        mLogOnHashMap.put("platform", Constants.PLAFORM);


        // 网络计时器及线程
        TimeOutHandler.pDialogUtils = pDialogUtils;
        pDialogUtils.show();
        timeChecker.start();
        // 获取sign签名
        Constants.SIGN = SignUtil.getInstance().getSign(mLogOnHashMap);
        HttpClient.posttwo(OkeHomeConsumptionApi.ELVDOU_PAYOFALIPAY, lifeUserTye, new JsonResponseHandler() {

            @Override
            public void onSuccess(int statusCode, String content) {
                // TODO Auto-generated method stub
                super.onSuccess(statusCode, content);
                timeChecker.check();
                pDialogUtils.dismiss();
                TimeOutHandler.pDialogUtils = null;
                try {
                    JSONTokener jsonT = new JSONTokener(content);
                    JSONObject jsonOBJ = (JSONObject) jsonT.nextValue();
                    String code = jsonOBJ.optString("code");
                    String message = jsonOBJ.optString("message");
                    if (code.equals("N000000")) {
                        orderInfo = jsonOBJ.optString("data");
                        // 必须异步调用
                        Thread payThread = new Thread(payRunnable);
                        payThread.start();
                        //  showShortToast("正常吊起微信支付");
                        // token过期
                    }
                } catch (JSONException ex) {
                    LogUtils.e("DownPaymentPost", "支付宝请求失败 ");
                }
            }
        });
    }

    /**
     * @param
     * @return w支付宝款项支付保证金
     * 创建时间：2017/3/7 12:29
     */
    public void zhifubao_pay(String lifeUserTye, String amount) {
        // TODO Auto-generated method stub
        // post传参使用的HashMap
        HashMap<String, String> paramMaps = new HashMap<String, String>();
        // 生成sign值所使用的HashMap
        final HashMap<String, String> mLogOnHashMap = new HashMap<String, String>();
        // mParamHashMap.put("token", Constants.TOKEN);
        mLogOnHashMap.put("v", Constants.APPVERSION);
        mLogOnHashMap.put("t", Constants.TIME);
        mLogOnHashMap.put("deviceToken", Constants.DEVICETOKEN);
        mLogOnHashMap.put("client", Constants.CLIENT);
        LogUtils.e("PayPost time =", Constants.TIME);
        mLogOnHashMap.put("deviceId", URLEntity.getInstance().getImei());
        mLogOnHashMap.put("platform", Constants.PLAFORM);


        mLogOnHashMap.put("lifeUserTye", String.valueOf(lifeUserTye));
        paramMaps.put("lifeUserTye", String.valueOf(lifeUserTye));

        mLogOnHashMap.put("money", String.valueOf(amount));
        paramMaps.put("money", String.valueOf(amount));

        mLogOnHashMap.put("ip", "192.168.0.1");
        paramMaps.put("ip", "192.168.0.1");

        mLogOnHashMap.put("optType", "1");
        paramMaps.put("optType", "1");


        // 网络计时器及线程
        TimeOutHandler.pDialogUtils = pDialogUtils;
        pDialogUtils.show();
        timeChecker.start();
        // 获取sign签名
        Constants.SIGN = SignUtil.getInstance().getSign(mLogOnHashMap);
        HttpClient.get(OkeHomeConsumptionApi.ELVDOU_ALIPAY, paramMaps, new JsonResponseHandler() {

            @Override
            public void onSuccess(int statusCode, String content) {
                // TODO Auto-generated method stub
                super.onSuccess(statusCode, content);
                timeChecker.check();
                pDialogUtils.dismiss();
                TimeOutHandler.pDialogUtils = null;
                try {
                    JSONTokener jsonT = new JSONTokener(content);
                    JSONObject jsonOBJ = (JSONObject) jsonT.nextValue();
                    String code = jsonOBJ.optString("code");
                    String message = jsonOBJ.optString("message");
                    if (code.equals("N000000")) {
                        orderInfo = jsonOBJ.optString("data");

                        // 必须异步调用
                        Thread payThread = new Thread(payRunnable);
                        payThread.start();
                        finish();
                        //  showShortToast("正常吊起微信支付");
                        // token过期
                    }
                } catch (JSONException ex) {
                    LogUtils.e("DownPaymentPost", "付首期款请求失败 ");
                }
            }
        });
    }

    final Runnable payRunnable = new Runnable() {

        @Override
        public void run() {
            PayTask alipay = new PayTask(PayAmountActivity.this);
            Map<String, String> result = alipay.payV2(orderInfo, true);
            Log.i("msp", result.toString());
            Message msg = new Message();
            msg.what = SDK_PAY_FLAG;
            msg.obj = result;
            mzfbHandler.sendMessage(msg);
        }
    };
    @SuppressLint("HandlerLeak")
    private Handler mzfbHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 2: {
                    @SuppressWarnings("unchecked")
                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                    String resultStatus = authResult.getResultStatus();
                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                    if (TextUtils.equals(resultStatus, "9000") ) {
                        // 获取alipay_open_id，调支付时作为参数extern_token 的value
                        // 传入，则支付账户为该授权账户
                        Toast.makeText(PayAmountActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                        finish();
                        startActivity(PayResultActivity.class);
                    } else {
                        // 其他状态值则为授权失败
                        Toast.makeText(PayAmountActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }
            }

        }


    };

    /**
     * @param
     * @return 积分支付查询
     */
    public void integral2cash(final String price) {
        // TODO Auto-generated method stub
        // post传参使用的HashMap
        HashMap<String, String> paramMaps = new HashMap<String, String>();
        // 生成sign值所使用的HashMap
        final HashMap<String, String> mLogOnHashMap = new HashMap<String, String>();
        // mParamHashMap.put("token", Constants.TOKEN);
        mLogOnHashMap.put("v", Constants.APPVERSION);
        mLogOnHashMap.put("t", Constants.TIME);
        mLogOnHashMap.put("deviceToken", Constants.DEVICETOKEN);
        mLogOnHashMap.put("client", Constants.CLIENT);
        LogUtils.e("PayPost time =", Constants.TIME);
        mLogOnHashMap.put("deviceId", URLEntity.getInstance().getImei());
        mLogOnHashMap.put("platform", Constants.PLAFORM);

        paramMaps.put("amount", price);


        // 网络计时器及线程
        TimeOutHandler.pDialogUtils = pDialogUtils;
        pDialogUtils.show();
        timeChecker.start();
        // 获取sign签名
        Constants.SIGN = SignUtil.getInstance().getSign(mLogOnHashMap);
        HttpClient.get(OkeHomeConsumptionApi.ELVDOU_INTEGRAL2CASH, paramMaps, new JsonResponseHandler() {

            @Override
            public void onSuccess(int statusCode, String content) {
                // TODO Auto-generated method stub
                super.onSuccess(statusCode, content);
                timeChecker.check();
                pDialogUtils.dismiss();
                TimeOutHandler.pDialogUtils = null;
                try {
                    JSONTokener jsonT = new JSONTokener(content);
                    JSONObject jsonOBJ = (JSONObject) jsonT.nextValue();
                    String code = jsonOBJ.optString("code");
                    String message = jsonOBJ.optString("message");
                    if (code.equals("N000000")) {
                        JSONObject jsonobj = jsonOBJ.optJSONObject("data");
                        String subtractIntegral = jsonobj.optString("subtractIntegral");
                        Gson gson = new Gson();
                        Map<String, Object> mapjson = new HashMap<>();
                        mapjson.put("amount", price);
                        mapjson.put("ip", "192.168.0.1");
                        mapjson.put("optType", "1");//必传,操作类型[1-app端，2-微信小程序端]
                        mapjson.put("payType", "3");//支付类型,1-连连，2-微信，3-积分,该字段目前可以传
                        mapjson.put("qrCodeStr", er_code);//二维码对应的字符串序列 ,
                        mapjson.put("shopId", shopid);//店铺id
                        mapjson.put("integral", subtractIntegral);//抵扣积分数
                        String lifeCityCopartnerDTO = gson.toJson(mapjson);//map转json字符串
                        integral(lifeCityCopartnerDTO);
                    }
                } catch (JSONException ex) {
                    LogUtils.e("integral2cash", "积分支付查询 ");
                }
            }
        });
    }

    /**
     * @param
     * @return 积分支付
     */
    public void integral(String lifeCityCopartnerDTO) {
        // TODO Auto-generated method stub
        // post传参使用的HashMap
        HashMap<String, String> paramMaps = new HashMap<String, String>();
        // 生成sign值所使用的HashMap
        final HashMap<String, String> mLogOnHashMap = new HashMap<String, String>();
        // mParamHashMap.put("token", Constants.TOKEN);
        mLogOnHashMap.put("v", Constants.APPVERSION);
        mLogOnHashMap.put("t", Constants.TIME);
        mLogOnHashMap.put("deviceToken", Constants.DEVICETOKEN);
        mLogOnHashMap.put("client", Constants.CLIENT);
        LogUtils.e("PayPost time =", Constants.TIME);
        mLogOnHashMap.put("deviceId", URLEntity.getInstance().getImei());
        mLogOnHashMap.put("platform", Constants.PLAFORM);
        // 网络计时器及线程
        TimeOutHandler.pDialogUtils = pDialogUtils;
        pDialogUtils.show();
        timeChecker.start();
        // 获取sign签名
        Constants.SIGN = SignUtil.getInstance().getSign(mLogOnHashMap);
        HttpClient.posttwo(OkeHomeConsumptionApi.ELVDOU_INTEGRAL, lifeCityCopartnerDTO, new JsonResponseHandler() {

            @Override
            public void onSuccess(int statusCode, String content) {
                // TODO Auto-generated method stub
                super.onSuccess(statusCode, content);
                timeChecker.check();
                pDialogUtils.dismiss();
                TimeOutHandler.pDialogUtils = null;
                try {
                    JSONTokener jsonT = new JSONTokener(content);
                    JSONObject jsonOBJ = (JSONObject) jsonT.nextValue();
                    String code = jsonOBJ.optString("code");
                    String message = jsonOBJ.optString("message");
                    if (code.equals("N000000")) {
                        toast("支付成功");
                        finish();
                        startActivity(PayResultActivity.class);
                    }
                } catch (JSONException ex) {
                    LogUtils.e("integral", "积分支付 ");
                }
            }
        });
    }

    /**
     * @param
     * @return 连连支付（）
     * 创建时间：2017/3/7 12:29
     */
    public void PayPost(String lifeCityCopartnerDTO) {
        // TODO Auto-generated method stub
        // post传参使用的HashMap
        HashMap<String, String> paramMaps = new HashMap<String, String>();
        // 生成sign值所使用的HashMap
        final HashMap<String, String> mLogOnHashMap = new HashMap<String, String>();
        // mParamHashMap.put("token", Constants.TOKEN);
        mLogOnHashMap.put("v", Constants.APPVERSION);
        mLogOnHashMap.put("t", Constants.TIME);
        mLogOnHashMap.put("deviceToken", Constants.DEVICETOKEN);
        mLogOnHashMap.put("client", Constants.CLIENT);
        LogUtils.e("PayPost time =", Constants.TIME);
        mLogOnHashMap.put("deviceId", URLEntity.getInstance().getImei());
        mLogOnHashMap.put("platform", Constants.PLAFORM);

        // 网络计时器及线程
        TimeOutHandler.pDialogUtils = pDialogUtils;
        pDialogUtils.show();
        timeChecker.start();
        // 获取sign签名
        Constants.SIGN = SignUtil.getInstance().getSign(mLogOnHashMap);
        HttpClient.posttwo(OkeHomeConsumptionApi.ELVDOU_LIANLIAN, lifeCityCopartnerDTO, new JsonResponseHandler() {

            @Override
            public void onSuccess(int statusCode, String content) {
                // TODO Auto-generated method stub
                super.onSuccess(statusCode, content);
                timeChecker.check();
                pDialogUtils.dismiss();
                TimeOutHandler.pDialogUtils = null;
                try {
                    JSONTokener jsonT = new JSONTokener(content);
                    JSONObject jsonOBJ = (JSONObject) jsonT.nextValue();
                    String code = jsonOBJ.optString("code");
                    String message = jsonOBJ.optString("message");
                    if (code.equals("N000000")) {
                        JSONObject jSONObject = jsonOBJ.optJSONObject("data");
                        PayOrder payOrder = JsonUtils.object(jSONObject.toString(), PayOrder.class);
                        String content4Pay = BaseHelper.toJSONString(payOrder);
                        MobileSecurePayer msp = new MobileSecurePayer();
                        bundle.putString("pay", "ProjectPay");
                        boolean bRet = msp.payAuth(content4Pay, mHandler,
                                com.zhsj.OkeHomeConsumption.common.lianlianpay.utils.Constants.RQF_PAY, getActivity(), false);
                    } else if (code.equals(Constants.STATUSTOKENERROR)) {
                        // token过期
                        if (!message.equals("null")) {
                            toast(message);
                        }
                    } else {
                        if (!message.equals("null")) {
                            toast(message);
                        }
                    }
                } catch (JSONException ex) {
                    LogUtils.e("DownPaymentPost", "付首期款请求失败 ");
                }
            }

            @Override
            public void onFailure(Throwable e) {
                // TODO Auto-generated method stub
                super.onFailure(e);
                timeChecker.check();
                pDialogUtils.dismiss();
                TimeOutHandler.pDialogUtils = null;
                LogUtils.e("onFailure", "" + e.toString());
            }
        });
    }

    /**
     * double转String,保留小数点后两位
     *
     * @param num
     * @return
     */
    public static String doubleToString(double num) {
        //使用0.00不足位补0，#.##仅保留有效位
        return new DecimalFormat("0.00").format(num);
    }

    private Handler mHandler = createHandler();

    private Handler createHandler() {
        return new Handler() {
            public void handleMessage(Message msg) {
                String strRet = (String) msg.obj;
                switch (msg.what) {
                    case com.zhsj.OkeHomeConsumption.common.lianlianpay.utils.Constants.RQF_PAY: {
                        JSONObject objContent = BaseHelper.string2JSON(strRet);
                        String retCode = objContent.optString("ret_code");
                        String retMsg = objContent.optString("ret_msg");
                        // 成功
                        if (com.zhsj.OkeHomeConsumption.common.lianlianpay.utils.Constants.RET_CODE_SUCCESS.equals(retCode)) {
                            // TODO 卡前置模式返回的银行卡绑定协议号，用来下次支付时使用，此处仅作为示例使用。正式接入时去掉
                            showAlertMsgDialog(retMsg, "支付结果", 0);
                            break;
                        } else if (com.zhsj.OkeHomeConsumption.common.lianlianpay.utils.Constants.RET_CODE_PROCESS.equals(retCode)) {
                            // TODO 处理中，掉单的情形
                            String resulPay = objContent.optString("result_pay");
                            if (com.zhsj.OkeHomeConsumption.common.lianlianpay.utils.Constants.RESULT_PAY_PROCESSING
                                    .equalsIgnoreCase(resulPay)) {
//                                showShortToast(objContent.optString("ret_msg"));
                                showAlertMsgDialog(resulPay, "支付结果", 1);
                            }
                        } else if (com.zhsj.OkeHomeConsumption.common.lianlianpay.utils.Constants.RET_CODE_RENZHENGFAIL.equals(retCode)) {
                            // TODO 处理中，掉单的情形
                            String resulPay = objContent.optString("result_pay");
                            if (com.zhsj.OkeHomeConsumption.common.lianlianpay.utils.Constants.RESULT_PAY_PROCESSING
                                    .equalsIgnoreCase(resulPay)) {
//                                showShortToast(objContent.optString("ret_msg"));
                                showAlertMsgDialog("身份证号格式有误", "支付结果", 1);
                            }
                        } else {
                            // TODO 失败
                            showAlertMsgDialog(retMsg, "支付结果", 1);
                        }
                    }
                    break;
                }
                super.handleMessage(msg);
            }
        };
    }

    public void showAlertMsgDialog(String msg, String title, final int tag) {

        new MessageDialog.Builder(this)
                .setTitle(msg) // 标题可以不用填写
                .setMessage(title)
                .setConfirm("确定")
                .setCancel(null) // 设置 null 表示不显示取消按钮
                //.setAutoDismiss(false) // 设置点击按钮后不关闭对话框
                .setListener(new MessageDialog.OnListener() {

                    @Override
                    public void onConfirm(Dialog dialog) {
                        finish();
                    }

                    @Override
                    public void onCancel(Dialog dialog) {
                        toast("取消了");
                    }
                })
                .show();
    }

}
